<template>
  <div class="trendContainer">
    <div class="loading-box" v-show="show">
    loading……
    </div>
    <div class="header-box">
      <div class="dialog-title">
<!--        {{wellName}}  - -->
        Tags Trend</div>

    </div>
    <div class="top-box">
      <div>
        <span>Start:</span>
        <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="Please enter"
            :disabled-date="disabledStartDate"
            :disabled="form.endTime && form.startTime > form.endTime"
            @change="changeStartTime"
        ></el-date-picker>
      </div>
      <div>
        <span>End:</span>
        <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="Please enter"
            :disabled="form.startTime && form.endTime < form.startTime"
            @change="changeEndTime"
        ></el-date-picker>
      </div>
      <div class="ml-1">

        <el-button type="primary" @click="getTrend">Search</el-button>
        <el-button type="primary" @click="config" >Config</el-button>
        <!-- <el-button type="primary" @click="exportFiles">Export</el-button> -->
        <el-button type="default" @click="closeWindow">Close Window</el-button>
      </div>
    </div>
    <div class="content-box" >
      <el-dialog title="Config" v-model="dialogTableVisible" @close="settingCancel" :z-index="1">
        <div class="dialog-content">
          <el-table
              :data="tableData"
              max-height="600px"
              style="width: 100%;">
            <el-table-column
                prop="tagName"
                label="Tag Name"
                width="280">
            </el-table-column>
            <el-table-column
                prop="axes"
                label="Axes"
            >

              <template v-slot:default="props">
                <!--              {{props.row.axes}}-->
                <el-select v-model="props.row.axes" placeholder="" >
                  <el-option-group  label="First coordinate system">
                    <el-option label="Primary Vertical Axis (Left y-axis)" value="ESP-1"></el-option>
                    <el-option label="Secondary Vertical Axis (Right y-axis)" value="ESP-2"></el-option>
                  </el-option-group>
                  <el-option-group  label="Second coordinate system">
                    <el-option label="Primary Vertical Axis (Left y'-axis)" value="ESP-3"></el-option>
                    <el-option label="Secondary Vertical Axis (Right y'-axis)" value="ESP-4"></el-option>
                  </el-option-group>

<!--                  <el-option-->
<!--                      v-for="item in options"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value">-->
<!--                  </el-option>-->
                </el-select>
              </template>

            </el-table-column>
            <el-table-column
                width="180"
                prop="Review"
                label="Review">
              <template v-slot:default="props">
                <el-popconfirm
                    confirm-button-text="Yes"
                    cancel-button-text="No"
                    icon-color="#626AEF"
                    title="Are you sure to delete this?"
                    @confirm="confirmEvent(props.row)"
                    @cancel="cancelEvent(props.row)"
                >
                  <template #reference>
                    <el-button  type="text" style="color: red" @click="deleteItem(props.row)" >delete</el-button>
                  </template>
                </el-popconfirm>


              </template>
            </el-table-column>
          </el-table>
        </div>

        <div>
          <el-button @click="settingCancel">Cancel</el-button>
          <el-button type="primary" @click="settingSubmit">Submit</el-button>
        </div>

      </el-dialog>
      <div id="main" class="trendArea">
      </div>
    </div>
  </div>

</template>
<script>
import * as echarts from "echarts";
import {getTrendTimeValueByTagName} from '@/api/index'
import { ElLoading } from 'element-plus'
import {nextTick} from "vue";
export default {
  name: "TrendComparison",
  data(){

    return{
      show:false,
      wellName:"",
      form: {
        startTime:localStorage.getItem('startTime') ? localStorage.getItem('startTime'): "",
        // endTime: this.convertBeijingToCalgary(new Date()),
        endTime:localStorage.getItem('endTime') ? localStorage.getItem('endTime'): this.convertBeijingToCalgary(new Date()),
        tagName:""
      },
      tagName:"",
      xData:[],
      dateList:[],
      valueList:[],
      dataListArray:[],
      totalLegend:[],
      lineColor:[
        '#fe7501','#00d4fa','#f371ff','#4ad400','#bb1504','#31adf3','#0345e3',
        '#9ce6fd','#868ecb','#f90aaf','#f9cdd8',
        '#fc7298','#5a91f5','#b6e959','#4ec4d6',
        '#fed505','#f59f83','#a00386','#5b63ff','#b29bc3','#7de7a2','#fec503'],
      myChart:"",
      dialogTableVisible:false,
      tableData:[],
      // options: [{
      //   value: 'ESP-1',
      //   label: 'WHT TCF HZ Valve % Csg Temp'
      // }, {
      //   value: 'ESP-2',
      //   label: 'WHP Prd Heel Prd Toe Stm Heel Csg'
      // }, {
      //   value: 'ESP-3',
      //   label: 'Flow Rate m³/hr'
      // }, {
      //   value: 'ESP-4',
      //   label: 'Amps'
      // }],
      confirmDelete:false,
      sortedDates:[],
      seriesList:[],
      legendGroup:[[],[],[],[]],
      deleteTagName:'',//标记要删除的tagName
      copyLegend:[],
      doubleY:false,
      loading:false,
      timer:null
    }
  },
  created() {
    this.show = true;
    this.initTime();//初始化并存储起止时间
    this.checkWell();//判断传递相同井可进行后续操作，否则清空本地数据
    // 判断传递有效的tagName 进行请求，否则进行提示
    this.setTagName();
    document.title = 'Tags-Trend';
  },

  mounted() {

    window.addEventListener("resize", this.handleChartResize);
  },
  watch:{
    tagName:{
      handler(newVal,oldVal){
        if(newVal && newVal.length > 0){
          this.getTrendTimeValueByTagNameFun(this.form)
        }
      },immediate:true
    }
  },
  beforeUnmount() {
    if(this.myChart){
      this.myChart.dispose()
    }
  },
  methods:{

    async getTrend(){

     this.show = true

      const num = this.getStorage('legend')
      //存储设置数据
      this.setStorage('setting',this.getStorage('dataList'))

      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }

      let legend = this.getStorage('legend')
      if(legend && legend.length > 0){
        legend.map(params =>{

          let paramsObj = {
            startTime:this.form.startTime,
            endTime:endTime,
            tagName:params
          }

          //上面取完值后，清除本地数据
          localStorage.removeItem('legend')
          localStorage.removeItem('dataList')
          localStorage.removeItem('xData')

          this.Timer = setTimeout(() => {

            if(num.length === this.getStorage('legend').length){

              this.show = false;
              clearTimeout(this.Timer)
            }
          }, 5000)
          this.getTrendTimeValueByTagNameFun(paramsObj)
        })
      }

    },
    settingSubmit(){

      this.dialogTableVisible = false;
      this.deleteTagName = "";
      // 删除提交后更新本地图例数据
      this.aftersettingSubmit();
    },
    aftersettingSubmit(){
      // 提交弹窗更新本地存储内容
      this.setStorage('legend',this.copyLegend)
      this.setStorage('dataList',this.tableData)
      this.setStorage('setting',this.getStorage('dataList'))
      this.getLocationDataInitChart()

    },
    config(){
      this.deleteTagName = "";
      // 显示弹窗时本地取出列表数据进行渲染
      this.dialogTableVisible = true;
      this.tableData = this.getStorage('dataList');
      this.copyLegend = this.getStorage('legend');
    },
    confirmEvent(row){
      // 确认删除，先更新this.tableData的数据
      this.confirmDelete = true

      this.tableData.forEach((item,index)=>{
        if(item.tagName === this.deleteTagName){
          this.tableData.splice(index,1)
          this.copyLegend.splice(index,1)
        }
      })
    },
    cancelEvent() {
      this.confirmDelete =false
      this.deleteTagName = ""
    },
    deleteItem(row){
      // 记录要删除的tagName
      this.deleteTagName = row.tagName;
    },
    settingCancel(){
      this.dialogTableVisible = false;
      this.tableData =  this.getStorage('dataList')
    },
    async getTrendTimeValueByTagNameFun(params){
      const res = await getTrendTimeValueByTagName(params)

      if(res.code !== 200){
        this.show = false
        return this.$message.error(res.msg);
      }else{
        // 结果不为空对象
        if(JSON.stringify(res.data) === '{}'){
          this.show = false;
          //当返回的结果没有值loading 隐藏，如果本地已有数据，刷新页面。没有则只提示
          if(this.getStorage('legend') && this.getStorage('legend').length > 0){
            this.getTrend()
            return this.$message.warning("no data")
          }else{
            return this.$message.warning("no data")
          }

        }else{
          res.data.axes = 'ESP-1';
          const setting = this.getStorage('setting')
          if(setting && setting.length){
            setting.forEach(item=>{
              if(res.data.tagName === item.tagName){
                res.data.axes = item.axes
              }
            })
          }
            // 存储结果
            this.localData(res.data);
        }

      }
    },
    openFullScreen2() {
      this.loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'custom-loading', // 可选，用于自定义类名以便修改样式
      })
    },
    localData(data){
      // 存储趋势图x轴坐标，(注意：此坐标会在时间改变后并执行搜索的时候进行重置)
      if(this.getStorage('xData') === null){
        this.setStorage('xData',data.timeList)
      }

      let found=null;
      // 存储图例
      if(this.getStorage('legend') === null){
        let legend = [];
            legend.push(data.tagName);
        this.setStorage('legend',legend)
      }else{
        let legend = this.getStorage('legend')

        found = legend.find((item,index) => item === data.tagName);// 是否已存在

        if(!found){
          legend.push(data.tagName)
          this.setStorage('legend',legend)
        }
      }

      //存储数据列表
      if(this.getStorage('dataList') === null){
        let dataList = [];
            dataList.push(data)
        this.setStorage('dataList',dataList)
      }else{
        let dataList = this.getStorage('dataList')
        if(!found){
          dataList.push(data)
          this.setStorage('dataList',dataList)
        }
      }

      this.getLocationDataInitChart()
    },
    setStorage(key,data){
      localStorage.setItem(key,JSON.stringify(data))
    },
    getStorage(key){
      return JSON.parse(localStorage.getItem(key))
    },
    closeWindow(){
      this.clearLocalData()
      window.close()
    },

    clearLocalData(){
      localStorage.removeItem('dataList');
      localStorage.removeItem('endTime');
      localStorage.removeItem('legend');
      localStorage.removeItem('setting');
      localStorage.removeItem('startTime');
      localStorage.removeItem('wellName');
      localStorage.removeItem('xData');
    },
    // 存储起止时间
    saveStartTimeEndTime(){
      localStorage.setItem('startTime',this.form.startTime)
      localStorage.setItem('endTime',this.form.endTime)
    },

    getLocationDataInitChart(){
      let dataList = this.getStorage('dataList');
      let xData = this.getStorage('xData');
      let legendGroup = [[],[],[],[]];
      let seriesList = [];
      let flag = null;
       dataList.find(item=> {
        if(item.axes === 'ESP-3' || item.axes === 'ESP-4'){
          flag = true
        }
      })



      dataList.forEach((item,i)=>{
          if(item.axes === 'ESP-1'){
            legendGroup[0].push(item.tagName)
            seriesList.push({
              name:item.tagName,
              type: 'line',
              showSymbol: false,
              data: item.valueList,
              itemStyle:{
                color:this.lineColor[i]
              },
              xAxisIndex: 0,
              yAxisIndex:0,
              gridIndex:0
            })
          }else if(item.axes==='ESP-2'){

            legendGroup[1].push(item.tagName)
            seriesList.push({
              name:item.tagName,
              type: 'line',
              showSymbol: false,
              data: item.valueList,
              itemStyle:{
                color:this.lineColor[i]
              },
              xAxisIndex:0,
              yAxisIndex:1,
              gridIndex:0
            })
          }else if(item.axes==='ESP-3'){

            legendGroup[2].push(item.tagName)
            seriesList.push({
              name:item.tagName,
              type: 'line',
              showSymbol: false,
              data:item.valueList,
              itemStyle:{
                color:this.lineColor[i]
              },
              xAxisIndex: 1,
              yAxisIndex: 2,
              gridIndex:1
            })
          }else{
            legendGroup[3].push(item.tagName)

            seriesList.push({
              name:item.tagName,
              type: 'line',
              showSymbol: false,
              data: item.valueList,
              itemStyle:{
                color:this.lineColor[i]
              },
              xAxisIndex: 1,
              yAxisIndex: 3,
              gridIndex:1
            })
          }
      })
      this.myChart = this.initEcharts(xData,seriesList,legendGroup)
      // const option =  this.myChart.getOption()
      //
      // if(flag){
      //   option.grid = [{
      //     left: "50px",
      //     right: "30px",
      //     top: "7%",
      //     height: "40%",
      //     containLabel: true
      //   },{
      //     left: "50px",
      //     right: "30px",
      //     top: "60%",
      //     height: "33%",
      //     containLabel: true
      //   }]
      //   option.xAxis[1].show = true
      // }else{
      //   option.grid = [{
      //     left: "50px",
      //     right: "30px",
      //     top: "7%",
      //     height: "80%",
      //     containLabel: true
      //   }]
      //   option.xAxis[1].show = false
      // }

      // this.myChart.setOption(option)
    },
    checkWell(){
      this.wellName = this.$route.query.wellName;
      if(localStorage.getItem('wellName') == null){
        localStorage.setItem('wellName',this.$route.query.wellName)
      }
    },
    // check
    // checkWell(){
    //   this.wellName = this.$route.query.wellName;
    //   if(localStorage.getItem('wellName') == null){
    //     localStorage.setItem('wellName',this.$route.query.wellName)
    //   }else if(localStorage.getItem('wellName') === this.$route.query.wellName){
    //     //   后续正常渲染操作
    //     return true
    //   }else if(localStorage.getItem('wellName') !== this.$route.query.wellName){
    //     //  清除本地缓存，重新加载数据
    //     this.clearLocalData();// 注意 需要改成清除具体的内容
    //     localStorage.setItem('wellName',this.$route.query.wellName)
    //   }
    // },
    setTagName(){
      if(this.$route.query.key && this.$route.query.key.length > 0){
        this.form.tagName = this.$route.query.key
        this.tagName = this.$route.query.key
      }else{
        this.show= false;
        this.$message.warning('tagName!!')
        if(this.getStorage('legend') && this.getStorage('legend').length > 0){
          this.getTrend()
        }else{
          return false
        }
      }
    },
    handleChartResize() {
      if (!this.myChart) {
        return;
      }
      this.myChart.resize();
    },
    initEcharts(xData,seriesList,legendGroup){
      var chartDom = document.getElementById('main');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        legend:[
          {
            data:legendGroup[0],
            left:'left',
            textStyle:{
              color:'#ffffff'
            }
          },
          {
            data:legendGroup[1],
            left:'right',
            textStyle:{
              color:'#ffffff'
            }
          },
          {
            data:legendGroup[2],
            top:'50%',
            left:'left',
            textStyle:{
              color:'#ffffff'
            }
          },
          {
            data:legendGroup[3],
            top:'50%',
            left:'right',
            textStyle:{
              color:'#ffffff'
            }
          },
        ],
        tooltip: {
          trigger: 'axis',// 使用坐标轴触发，而不是数据项触发。这样可以显示所有系列的数据。

          formatter: function (params) {
            let str = '<div style="display:flex;align-items: flex-start;">' + params[0].name +'</div>';
            str += ''
            params.forEach((item)=>{
              if(item.seriesName !== "Warning"){
                str +=`<div style="display:flex;align-items: center;justify-content: space-between;"><div style="display:flex;align-items: center;justify-content: center;"><div style="width:0.5rem;height:.5rem;background:${item.color}; border-radius: 1rem;margin-top:0.1rem;margin-right:0.3rem"></div><span style="color:${item.color}">${item.seriesName}：</span></div><div><span style="color:${item.color};"><b>${item.data}</b></span> </div></div>`

              }
            })
            return str;
          }
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            gridIndex: 0,
          },
          {
            type: 'category',
            data: xData,
            gridIndex: 1,
            show:true
          }
        ],

        yAxis: [
          {
            type: 'value',
            position:'left',
            gridIndex: 0,
            scale: true, //自适应
          },
          {
            type: 'value',
            position:'right',
            gridIndex: 0
          },
          {
            type: 'value',
            position:'left',
            gridIndex: 1,
            top:'65%'
          },
          {
            type: 'value',
            position:'right',
            gridIndex: 1,
            top:'65%'
          },
        ],
        axisPointer: {
          link: [
            {
              xAxisIndex: 'all'
            }
          ],
          animation: false
        },
        grid: [
          {
            left: "50px",
            right: "30px",
            top: "7%",
            height: "40%",
            // containLabel: true
          }
          ,{
            left: "50px",
            right: "30px",
            top: "60%",
            height: "33%",
            // containLabel: true
          }
        ],
        series:seriesList,
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1]
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1]
          }
        ],
      };

      option && myChart.setOption(option);
      // 监听窗口大小改变事件
      window.addEventListener('resize', function() {
        myChart.resize();
      });
      this.show = false;
      return myChart
    },
    // ----------------------------------------------
    initTime(){
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      this.calculateTime(endTime, "day14", "0");

      this.saveStartTimeEndTime()
    },
    isDateObject(value) {
      return value instanceof Date;
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date
          .getDate()
          .toString()
          .padStart(2, "0");
      const hours = date
          .getHours()
          .toString()
          .padStart(2, "0");
      const minutes = date
          .getMinutes()
          .toString()
          .padStart(2, "0");
      const seconds = date
          .getSeconds()
          .toString()
          .padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    calculateTime(timeString, unit, type) {
      const time = new Date(timeString);
      const step = {
        hour: 28800000, // 8小时
        day: 86400000, // 一天
        day7: 604800000, // 一天
        day14: 1209600000, // 一天
        day30: 2592000000, // 一天
        day60: 5184000000 // 一天
      };
      if (type == "0") {
        // 减 计算startTime
        const newTime = new Date(time.getTime() - step[unit]);
        this.form.startTime = this.formatDate(newTime);
        localStorage.setItem('startTime',this.formatDate(newTime))
      } else {
        // 加 计算endtime
        const newTime = new Date(time.getTime() + step[unit]);
        this.form.endTime = this.formatDate(newTime);
      }


    },
// 将北京时间转换为卡尔加里时间
    convertBeijingToCalgary(beijingDate) {
      const options = {
        timeZone: 'America/Edmonton',  // 卡尔加里所属时区
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false                 // 强制24小时制
      };

      // 直接生成目标格式的字符串
      const formatter = new Intl.DateTimeFormat('en-CA', options);
      const calgaryTime = formatter.format(new Date())
          .replace(/(\d{4})-(\d{2})-(\d{2}),? (\d{2}:\d{2}:\d{2})/, '$1-$2-$3 $4');
      return calgaryTime
    },
    disabledStartDate(time) {
      if (this.form.endTime) {
        return time.getTime() > new Date(this.form.endTime).getTime();
      }
      return false;
    },
    changeStartTime(item) {
      const date = new Date(item);
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      month = month < 10? '0' + month : month;
      day = day < 10? '0' + day : day;
      hours = hours < 10? '0' + hours : hours;
      minutes = minutes < 10? '0' + minutes : minutes;
      seconds = seconds < 10? '0' + seconds : seconds;
      this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      localStorage.setItem('startTime', this.form.startTime)
      if (this.form.endTime && this.form.startTime > this.form.endTime) {
        this.form.startTime = this.form.endTime;
        localStorage.setItem('startTime', this.form.startTime)
      }
    },
    changeEndTime(value) {

      this.form.endTime = this.formatDate(value)
      if (this.form.startTime && this.form.endTime < this.form.startTime) {
        this.form.endTime = this.form.startTime;
      }
      localStorage.setItem('endTime',this.form.endTime)
    },
  }
}
</script>
<style scoped lang="scss">
.loading-box{
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  font-size: 1rem;
  top:0;
  left: 0;
  right: 0;
  bottom:0;
  background: rgb(0,0,0,0.6);
  z-index: 100;
  color: #ffffff;
}
.custom-loading {
  z-index: 1500; /* 或者比你想要的 Dialog 的 z-index 低一些 */
}
.trendContainer{
  width: 100vw;
  height: 100vh;
  .header-box{
    background: url("@/assets/header_bg.png") no-repeat;
    background-position: center center;
    height: 5h;
    font-size: 1.8rem;
    padding-top: 0.5rem;
    color: rgb(17, 137, 229);
  }
  .top-box{
    padding-top: 1vh;
    height: 5vh;
    display: flex;
    justify-content: flex-start;
    span{
      padding-left: 1vw;
      padding-right: 0.2vw;
      color: #eeeeee;
    }
  }
  .content-box{
    height: 94vh;
    padding:10px;

    .dialog-content{

      //border: 1px solid #ff0000;
    }
  }

  .ml-1{
    margin-left: 1vw;
  }
  .trendArea{
    width: 100%;
    height: 90vh;
  }
}
</style>